from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView


class OAuthQQLoginView(APIView):
    def get(self,request):
        #1,获取参数
        state = request.query_params.get("state","/")

        #2,创建qq对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                client_secret=settings.QQ_CLIENT_SECRET,
                redirect_uri=settings.QQ_REDIRECT_URI,
                state=state)

        #3,返回qq登陆页面
        login_url = oauth_qq.get_qq_url()
        return Response({"auth_url":login_url})


class OAuthQQUserView(APIView):
    def get(self,request):
        #1,获取参数code,校验
        code = request.query_params.get("code")
        if not code:
            return Response("code丢失了")

        #2,根据code获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state="/")
        access_token = oauth_qq.get_access_token(code)


        #3,根据access_token获取openid
        openid = oauth_qq.get_open_id(access_token)
        print("openid = %s"%openid)
        return Response("openid = %s"%openid)
